﻿#include "changeip.h"
#include "ui_changeip.h"
#include <QCoreApplication>
#include <QProcess>
#include <QString>
#include <QDebug>
#include <QMessageBox>
#include <QSettings>
#include "datasqlshow.h"
ChangeIp::ChangeIp(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ChangeIp)
{
    ui->setupUi(this);
    QStatusBar* zt = this->statusBar();
    //添加左侧信息
    QLabel* copyRight = new QLabel(QString::fromLocal8Bit("北京大学南昌创新研究院"), this);
    zt->addWidget(copyRight);
    #include <QSettings>
 
    //获取接口名称
  /*  QString interfaceName = getInterfaceByMacAddress(MAC);*/
   // QString ip = QString::fromLocal8Bit("172.16.28.168");  // 设置的静态IP地址
    QString subnet = QString::fromLocal8Bit("255.255.255.0 / 255.255.254.0 / 255.255.252.0");  // 子网掩码，表示CIDR格式（例如255.255.255.0表示24）
    QString gateway = QString::fromLocal8Bit("172.16.10.254 / 172.16.21.254 / 172.16.31.254");  // 默认网关
    QString dns1 = QString::fromLocal8Bit("202.101.224.68");  // 首选DNS服务器
    QString dns2 = QString::fromLocal8Bit("202.101.224.69");  // 备用DNS服务器
   // ui->lineEdit_7->setText(interfaceName);
    ui->lineEdit_3->setText(subnet);
    ui->lineEdit_4->setText(gateway);
    ui->lineEdit_5->setText(dns1);
    ui->lineEdit_6->setText(dns2);
    loadSettings();
    ui->lineEdit_2->setPlaceholderText(QString::fromLocal8Bit("IP为172.16.10\\172.16.20\\172.16.21"));
    ui->lineEdit->setPlaceholderText(QString::fromLocal8Bit("标准格式：2C-33-58-89-8B-7C"));
    ui->lineEdit_9->setPlaceholderText(QString::fromLocal8Bit("IP为172.16.28\\172.16.29\\172.16.30\\172.16.31"));
    ui->lineEdit_8->setPlaceholderText(QString::fromLocal8Bit("标准格式：2C-33-58-89-8B-7C"));
   // connect(qApp, &QCoreApplication::aboutToQuit, this, &ChangeIp::saveSettings);
    connect(ui->ipnum, SIGNAL(currentIndexChanged(int)), this, SLOT(onIpMacIndexChanged(int)));
   
    // 连接到 SQLite 数据库
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(QCoreApplication::applicationDirPath() + "/" + "pkuncii2.db");
    //qDebug() << dbPath;
    if (!db.open()) {

        qDebug() << "无法打开数据库:111" << db.lastError().text();
        return;
    }
    //试试添加数据库
    //ui->comboBox->addItem("ksen");
}
////选择姓名：
//void ChangeIp::choosename(const QString& strMName) {
//    string strSQL = "select * from ipmac where name = '" + strMName.toStdString() + "'; ";
//    vector<string> arrKey;
//    vector<vector<string>> arrValue;
//
//    int result = P2DModelOperatorr.FindAllData(strSQL, arrKey, arrValue);
//    if (arrValue.size() == 0 || arrValue.empty())
//    {
//        return;
//    }
//
//   // ui->lineEditName->setText(QString::fromStdString(arrValue[0][0]));
//
//}



ChangeIp::~ChangeIp()
{
    db.close();
    
    delete ui;
}
void ChangeIp::loadSettings() {
    QSettings settings("YourCompany", "YourApp");
    ui->lineEdit_2->setText(settings.value("lastInput2").toString());
    ui->lineEdit->setText(settings.value("lastInput1").toString());
    ui->lineEdit_9->setText(settings.value("lastInput9").toString());
    ui->lineEdit_8->setText(settings.value("lastInput8").toString());
    ui->lineEdit_7->setText(settings.value("lastInput7").toString());
}

void ChangeIp::saveSettings() {
    QSettings settings("YourCompany", "YourApp");
    settings.setValue("lastInput2", ui->lineEdit_2->text());
    settings.setValue("lastInput1", ui->lineEdit->text());
    settings.setValue("lastInput9", ui->lineEdit_9->text());
    settings.setValue("lastInput8", ui->lineEdit_8->text());
    settings.setValue("lastInput7", ui->lineEdit_7->text());

}


void ChangeIp::queryDatabase(const QString& dbPath, QString& dbname, QString& index) {
    

    // 执行查询
    

    if (index == "100") {
        ui->ipnum->clear();
    
    QString mingliang2 = "SELECT COUNT(*) AS count FROM ipmac  WHERE name = \'" + dbname + "\'";

    QSqlQuery* countQuery = new QSqlQuery();
    countQuery->prepare(mingliang2);
    countQuery->exec();
    int count=1;
    
    if (countQuery->next()) 
    {
        count = countQuery->value("count").toInt();
        qDebug() << "Name 'ksen' 出现的次数:" << count;
        if (count == 0) 
        {
            QMessageBox::information(nullptr, QString::fromLocal8Bit("信息"), QString::fromLocal8Bit("未搜索到该用户信息,请自行填写表格。"), QMessageBox::Ok);

        }
        
    }
    else {
        qDebug() << "Name 'ksen' 出现:";
        return;
    }
    //if (!countQuery.next()) {
    //    qDebug() << "查询失败:22111" << countQuery.lastError().text();
    //    //return;
    //}
    //在下拉列表中添加项目
    for (int i = 1; i <= count; ++i) { // 假设要添加10个序号，可以根据需要调整
        ui->ipnum->addItem(QString::number(i));
    }
}
    QString mingling = "SELECT * FROM ipmac WHERE name = \'" + dbname + "\' LIMIT " + index;
    QSqlQuery query(mingling);
    if (!query.exec()) {
        qDebug() << "查询失败:22111" << query.lastError().text();
        return;
    }
    // 读取并打印查询结果
    while (query.next()) {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        QString wiredip = query.value(4).toString();
        QString wiredmace = query.value(5).toString();
        wiredmace.replace(QString(":"), QString("-"));
        wiredmace = wiredmace.toUpper();
        QString wifiip = query.value(6).toString();
        QString wifimac = query.value(7).toString();
        wifimac.replace(QString(":"), QString("-"));
        wifimac = wifimac.toUpper(); 
        ui->lineEdit_2->setText(wiredip);
        ui->lineEdit->setText(wiredmace);

        ui->lineEdit_9->setText(wifiip);
        ui->lineEdit_8->setText(wifimac);
        qDebug() << "ID:" << id << "Name:" << name << wiredip << wiredmace << wifiip<< wifimac;
    }
   // return;

}
 
//切换下拉列表
void ChangeIp::onIpMacIndexChanged(int index)
{
    qDebug() << index;
    const QString path = QCoreApplication::applicationDirPath() + "/" + "pkuncii.db";
    QString dbPath = path;
    QString dbname = ui->lineEdit_7->text();
    QString num0;
    int index2 = index + 1;
    if (index == -1) {
        num0 = "1";
        queryDatabase(dbPath, dbname, num0);

    }
    num0 = QString::number(index2);
    for (int i = 0; i < 100; i++) {
        if (index == i) {
            queryDatabase(dbPath, dbname, num0);
        }
    }
    //if (index == -1) {
    //    num0="1";
    //     queryDatabase(dbPath, dbname, num0);
    //   
    //}
    //else if (index == 0) {
    //    num0 = "1";
    //    queryDatabase(dbPath, dbname, num0);
    //   
    //}
    //else if (index == 1) {
    //    num0 = "2";
    //    queryDatabase(dbPath, dbname, num0);
    //}
    //else if (index == 2) {
    //    num0 = "3";
    //    queryDatabase(dbPath, dbname, num0);
    //}
    //else if (index == 3) {
    //    num0 = "4";
    //    queryDatabase(dbPath, dbname, num0);
    //}
    //else if (index == 4) {
    //    num0 = "5";
    //    queryDatabase(dbPath, dbname, num0);
    //}
    //else if (index == 5) {
    //    num0 = "6";
    //    queryDatabase(dbPath, dbname, num0);
    //}


}
//检索获取相关信息，默认第一个
void ChangeIp::on_pushButton_search_clicked() {
    ui->lineEdit_2->clear();
    ui->lineEdit->clear();
    ui->lineEdit_9->clear();
    ui->lineEdit_8->clear();
    const QString path = QCoreApplication::applicationDirPath() + "/" + "pkuncii.db";
    qDebug() << path;
    QString dbPath = path;
    QString dbname = ui->lineEdit_7->text();
    QString initnum = "100";
    queryDatabase(dbPath, dbname, initnum);
    //queryDatabase(dbPath, dbname, initnum);

    
}


void ChangeIp::setStaticIP(const QString &interfaceName, const QString &ipAddress, const QString &netmask, const QString &gateway, const QString &dns1, const QString &dns2)
{
    QString command = QString("powershell -Command \"& { "
                              "Remove-NetIPAddress -InterfaceAlias '%1' -Confirm:$false; "
                              "New-NetIPAddress -InterfaceAlias '%1' -IPAddress '%2' -PrefixLength %3 -DefaultGateway '%4'; "
                              "Set-DnsClientServerAddress -InterfaceAlias '%1' -ServerAddresses ('%5', '%6'); "
                              "}\"")
                              .arg(interfaceName)
                              .arg(ipAddress)
                              .arg(netmask)
                              .arg(gateway)
                              .arg(dns1)
                              .arg(dns2);
    qDebug() << "1515";

    QProcess::execute(command);
}

void ChangeIp::on_pushButton_clicked()
{
    //QMessageBox::information(nullptr, QString::fromLocal8Bit("信息"), QString::fromLocal8Bit("正在配置请稍等"), QMessageBox::Ok);

    //无线的网络没有问题

    //QString adapterName = QString::fromLocal8Bit("WLAN");  // 网络接口名称，根据需要修改
    //QString ip = QString::fromLocal8Bit("172.16.28.168");  // 设置的静态IP地址
    //QString subnet = QString::fromLocal8Bit("255.255.252.0");  // 子网掩码，表示CIDR格式（例如255.255.255.0表示24）
    //QString gateway = QString::fromLocal8Bit("172.16.31.254");  // 默认网关
    //QString dns1 = QString::fromLocal8Bit("202.101.224.68");  // 首选DNS服务器
    //QString dns2 = QString::fromLocal8Bit("202.101.224.69");  // 备用DNS服务器
    //qDebug() << "15116616";
    //setManualIP(adapterName, ip, subnet, gateway, dns1, dns2);
     /* 识别电脑信息*/
    
    QString IP = ui->lineEdit_2->text();
    QString MAC11 = ui->lineEdit->text();
    //QString MAC11 = MAC.replace(QString("："), QString("-"));
    MAC11.replace(QString(":"), QString("-"));
    QString MAC=MAC11.toUpper();

    QString MAC22 = ui->lineEdit_8->text();
    MAC22.replace(QString(":"), QString("-"));
    QString MAC2 = MAC22.toUpper();
    QString IP2 = ui->lineEdit_9->text();


    QString interfaceName = getInterfaceByMacAddress(MAC);
   //// if (MAC==""&&(interfaceName == "" || interfaceName == QString::fromLocal8Bit("连接名")))
   // 
   // {
   //     QMessageBox::information(nullptr, QString::fromLocal8Bit("信息"), QString::fromLocal8Bit("未找到相应的MAC地址"), QMessageBox::Ok);
   //     
   // }
   // else{
    
   // ui->lineEdit_7->setText(interfaceName);
    if (IP.contains("172.16.10")) {
    QString subnet = QString::fromLocal8Bit("255.255.255.0");  // 子网掩码，表示CIDR格式（例如255.255.255.0表示24）
    QString gateway = QString::fromLocal8Bit("172.16.10.254");  // 默认网关
    QString dns1 = QString::fromLocal8Bit("202.101.224.68");  // 首选DNS服务器
    QString dns2 = QString::fromLocal8Bit("202.101.224.69");  // 备用DNS服务器
    setManualIP(interfaceName, IP, subnet, gateway, dns1, dns2);
    }
    else if (IP.contains("172.16.20")|| IP.contains("172.16.21")) {
        QString subnet = QString::fromLocal8Bit("255.255.254.0");  // 子网掩码，表示CIDR格式（例如255.255.255.0表示24）
        QString gateway = QString::fromLocal8Bit("172.16.21.254");  // 默认网关
        QString dns1 = QString::fromLocal8Bit("202.101.224.68");  // 首选DNS服务器
        QString dns2 = QString::fromLocal8Bit("202.101.224.69");  // 备用DNS服务器
        setManualIP(interfaceName, IP, subnet, gateway, dns1, dns2);

    }
    else if (IP.contains("172.16.31") || IP.contains("172.16.30") || IP.contains("172.16.29") || IP.contains("172.16.28")) {
        QString subnet = QString::fromLocal8Bit("255.255.252.0");  // 子网掩码，表示CIDR格式（例如255.255.255.0表示24）
        QString gateway = QString::fromLocal8Bit("172.16.31.254");  // 默认网关
        QString dns1 = QString::fromLocal8Bit("202.101.224.68");  // 首选DNS服务器
        QString dns2 = QString::fromLocal8Bit("202.101.224.69");  // 备用DNS服务器
        setManualIP(interfaceName, IP, subnet, gateway, dns1, dns2);
    }
    else {

    }
    //}
    qDebug() << "Interface Name for MAC Address" << MAC << "is" << interfaceName;

    QString interfaceName2 = getInterfaceByMacAddress(MAC2);
    if (IP2.contains("172.16.10")) {
        QString subnet = QString::fromLocal8Bit("255.255.255.0");  // 子网掩码，表示CIDR格式（例如255.255.255.0表示24）
        QString gateway = QString::fromLocal8Bit("172.16.10.254");  // 默认网关
        QString dns1 = QString::fromLocal8Bit("202.101.224.68");  // 首选DNS服务器
        QString dns2 = QString::fromLocal8Bit("202.101.224.69");  // 备用DNS服务器
        setManualIP(interfaceName2, IP2, subnet, gateway, dns1, dns2);
    }
    else if (IP2.contains("172.16.20") || IP2.contains("172.16.21")) {
        QString subnet = QString::fromLocal8Bit("255.255.254.0");  // 子网掩码，表示CIDR格式（例如255.255.255.0表示24）
        QString gateway = QString::fromLocal8Bit("172.16.21.254");  // 默认网关
        QString dns1 = QString::fromLocal8Bit("202.101.224.68");  // 首选DNS服务器
        QString dns2 = QString::fromLocal8Bit("202.101.224.69");  // 备用DNS服务器
        setManualIP(interfaceName2, IP2, subnet, gateway, dns1, dns2);

    }
    else if (IP2.contains("172.16.31")||IP2.contains("172.16.30")|| IP2.contains("172.16.29") || IP2.contains("172.16.28")) {
        QString subnet = QString::fromLocal8Bit("255.255.252.0");  // 子网掩码，表示CIDR格式（例如255.255.255.0表示24）
        QString gateway = QString::fromLocal8Bit("172.16.31.254");  // 默认网关
        QString dns1 = QString::fromLocal8Bit("202.101.224.68");  // 首选DNS服务器
        QString dns2 = QString::fromLocal8Bit("202.101.224.69");  // 备用DNS服务器
        setManualIP(interfaceName2, IP2, subnet, gateway, dns1, dns2);
    }
    else {

    }
    QMessageBox::information(nullptr, QString::fromLocal8Bit("信息"), QString::fromLocal8Bit("已完成网络配置，还是不行的话找综管万佳星"), QMessageBox::Ok);
    
    //QString interfaceName2 =interfaceName.toLocal8Bit();
    ///*if (!interfaceName.isEmpty())
    //{
    //    qDebug() << "Interface Name for MAC Address" << macAddress << "is" << interfaceName;
    //}
    //else
    //{
    //    qDebug() << "No interface found for MAC Address" << macAddress;
    //}*/

}

void ChangeIp::setManualIP(const QString& adapterName, const QString& ip, const QString& subnet, const QString& gateway, const QString& dns1, const QString& dns2)
{
    qDebug() << "1";
    QProcess process;
    QString command1;
    QString command2;
    QString command3;

    // 设置静态IP地址
    command1 = QString("netsh interface ip set address \"%1\" static %2 %3 %4")
        .arg(adapterName)
        .arg(ip)
        .arg(subnet)
        .arg(gateway);
    process.start(command1);
    process.waitForFinished();
    qDebug() << process.readAllStandardOutput();
    qDebug() << process.readAllStandardError();

    // 设置主DNS服务器
    command2 = QString("netsh interface ip set dns \"%1\" static %2")
        .arg(adapterName)
        .arg(dns1);
    process.start(command2);
    process.waitForFinished();
    qDebug() << process.readAllStandardOutput();
    qDebug() << process.readAllStandardError();

    // 设置备用DNS服务器
    command3 = QString("netsh interface ip add dns \"%1\" %2 index=2")
        .arg(adapterName)
        .arg(dns2);
    process.start(command3);
    process.waitForFinished();
    qDebug() << process.readAllStandardOutput();
    qDebug() << process.readAllStandardError();
}

QString ChangeIp ::getInterfaceByMacAddress(const QString& macAddress)
{
    QProcess process;
    QString command = "getmac /v /fo csv";

    process.start(command);
    process.waitForFinished();
    QString output = QString::fromLocal8Bit(process.readAllStandardOutput());

    QString interfaceName;
    QStringList lines = output.split('\n');

    // Find the interface name by matching the MAC address
    for (const QString& line : lines)
    {
        if (line.contains(macAddress, Qt::CaseInsensitive))
        {
            QStringList columns = line.split(',');
            if (columns.size() > 1)
            {
                interfaceName = columns[0].replace("\"", "").trimmed();
                break;
            }
        }
    }

    return interfaceName;
}

void ChangeIp::on_pushButton_DHCP_clicked() {
    qDebug() << QString::fromLocal8Bit("调整为DHCP");
    QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
    for (const QNetworkInterface& interface : interfaces)
    {
        // 获取接口名称
        QString interfaceName = interface.humanReadableName();
        setDhcp(interfaceName);

    }
}

//调整成自动获取模式
void ChangeIp::setDhcp(const QString& interfaceName) {
    QProcess process;
    QString command = QString("netsh interface ip set address \"%1\" dhcp").arg(interfaceName);
    process.start("cmd.exe", QStringList() << "/c" << command);
    process.waitForFinished();
    qDebug() << process.readAllStandardOutput();
    qDebug() << process.readAllStandardError();
    QString dnsCommand = QString("netsh interface ip set dns \"%1\" dhcp").arg(interfaceName);
    process.start("cmd.exe", QStringList() << "/c" << dnsCommand);
    process.waitForFinished();
    qDebug() << process.readAllStandardOutput();
    qDebug() << process.readAllStandardError();
}